﻿/*----------------------------------------------------------------------------------------
*
*  Copyright 2019, Gao Hai Hui, <fromzeropoint@126.com>.  All rights reserved.
*  https://gitee.com/helloworldghh/xoskit.git
*  Use of this source code is governed by a MIT license
*  that can be found in the License file.
*
----------------------------------------------------------------------------------------*/
#ifndef __XOSKIT_XOS_CORE_XOS_STL_SRC_MEM_POOL_AUTO_MAP_H__
#define __XOSKIT_XOS_CORE_XOS_STL_SRC_MEM_POOL_AUTO_MAP_H__

#include <map>
#include "fake_lock.h"

namespace xos_stl
{
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 
	// 直接继承，再加池需要的几个方法
	// 

	template< class KEY, class T, class MapLock = fake_lock >
    class auto_map : public std::map< KEY, T* >
    {
	public:
		typedef MapLock MAP_LOCK;
		typedef auto_map< KEY, T, MAP_LOCK > MAP;
		typedef typename MAP::const_iterator CONST_ITER;
		typedef typename MAP::iterator ITER;
        typedef std::map< KEY, T* > BASE;
	protected:
		MAP_LOCK _xos_stl_xos_map_lock;
    public:
        auto_map() : BASE()
		{
		}
        ~auto_map()
		{
		}
	public:
		void put_back_to_pool( bool bLock )
		{
            if( bLock )
            {
                lock();
            }
			for( ITER i = BASE::begin(); i != BASE::end(); )
			{
				T * pTemp = i++->second;
				pTemp->release();
				pTemp = 0;
			}
            BASE::clear();
            if( bLock )
            {
                un_lock();
            }
		}
		void un_lock()
		{
			_xos_stl_xos_map_lock.un_lock();
		}
		void lock()
		{
			_xos_stl_xos_map_lock.lock();
		}
    };

} // xos_stl

#endif // __XOSKIT_XOS_CORE_XOS_STL_SRC_MEM_POOL_AUTO_MAP_H__
